import express from 'express'
// const {Request,Response} = express
import { Request, Response } from 'express'
import { successMessage, errorMessage } from "../resTip/resTip"
import user from "../userDB/user"
const md5 = require("md5")

const router = express.Router()
router.post("/login", async (req: Request, res: Response) => {
  let password = typeof req.body.password === "string" ? req.query.password : null
  let username = typeof req.body.username === "string" ? req.query.username : null
  password = md5(password + "ttzxh").substring(0, 9)
  let data = await new user(<string>username, <string>password).login()
  if (data.length > 0) {
    let session: any = req.session
    session.username = username
    res.json(new successMessage(data))
  } else {
    res.json(new errorMessage("登陆失败"))
  }
})
router.get("/test", (req: Request, res: Response) => {
  let session: any = req.session
  console.log(session.username);
})
router.post("/register", async (req: Request, res: Response) => {
  let username = typeof req.body.username === "string" ? req.body.username : null
  let ifrepeat = await new user(username).search()
  if (ifrepeat.length > 0) {
    res.json(new errorMessage("注册失败,用户名重复"))
  } else {
    let password = typeof req.body.password === "string" ? req.body.password : null
    let status = md5("1" + "ttzxh").substring(0, 9)
    let realname = username
    password = md5(password + "ttzxh").substring(0, 9)
    let data = await new user(username, password, status, realname).register()
    data.affectedRows > 0 ?
      res.json(new successMessage("注册成功")) :
      res.json(new errorMessage("注册失败"))
  }
})

export default router
